﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using AGRTraining.za.co.agrtraining.model;

namespace AGRTraining.za.co.agrtraining.repository.Impl
{
    public class UserDAO : IDAO<User>
    {
        private AGRModelContainer agrDb = new AGRModelContainer();

        public void persist(User entity)
        {
            agrDb.Users.AddObject(entity);
        }

        public void remove(User entity)
        {
            agrDb.Users.DeleteObject(entity);
        }

        public void removeById(string code)
        {
            foreach (User student in agrDb.Users.Where(u => u.UserName == code))
            {
                agrDb.Users.DeleteObject(student);
            }
        }

        public void merge(User entity)
        {
            foreach (User user in agrDb.Users.Where(u => u.UserName == entity.UserName))
            {
                user.UserName = entity.UserName;
                user.UserPassword = entity.UserPassword;
                user.UserRoleCode = entity.UserRoleCode;
            }
        }

        public User findById(string code)
        {
            User user = new User();

            foreach (User usr in agrDb.Users.Where(u => u.UserName == code))
            {
                user = usr;
            }

            return user;
        }

        public IEnumerable<User> findAll()
        {
            var users = (from user in agrDb.Users
                            select user);

            return users;
        }

        public IEnumerable<User> findInRange(int firstResult, int maxResuslts)
        {
            var students = (from stud in agrDb.Users
                            select stud);

            return students.Skip(firstResult).Take(maxResuslts);
        }

        public long count()
        {
            var students = (from stud in agrDb.Users
                            select stud).ToList();

            return students.Count();
        }

        public void commit()
        {
            try
            {
                agrDb.SaveChanges();
            }
            catch
            {

            }
        }
    }
}